package demo1;

import java.util.Stack;

//逆波兰表达式(后缀表达式)
public class Test2 {
    public static void main(String[] args) {
        String[] str = new String[]{"1","2","3","+","4","*","+","5","-"};
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < str.length; i++) {
            //如果是数字就进入栈
            if (isNum(str[i])) {
                stack.push(Integer.parseInt(str[i]));
            //如果是运算符那就弹出栈顶的两个元素
            } else {
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch (str[i]) {
                    case "+" :
                        stack.push(num1 + num2);
                        break;
                    case "-" :
                        stack.push(num1 - num2);
                        break;
                    case "*" :
                        stack.push(num1 * num2);
                        break;
                    case "/" :
                        stack.push(num1 / num2);
                        break;
                }
            }
        }
        System.out.println(stack.pop());
    }
    //判断字符串是数字还是字符
    public static boolean isNum(String string) {
        if (string.equals("+") || string.equals("-") || string.equals("*") || string.equals("/")) {
            return false;
        }
        return true;
    }
}
